import 'dart:convert';
import 'package:tudouapp/blocs/product.dart';

import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import 'package:badges/badges.dart';

// import 'comp_prod_item.dart';
import '../../blocs/cart.dart';

import 'dart:math' as math;

class ProductListCateScreen extends StatefulWidget {
  final String param;
  ProductListCateScreen(this.param, {Key? key}) : super(key: key);
  _ProductListCateScreenState createState() => _ProductListCateScreenState();
}

class _ProductListCateScreenState extends State<ProductListCateScreen> {
  late Offset cartOffset;

  late ProductBloc listSourceRepository;

  GlobalKey cartKey = GlobalKey();
  GlobalKey rootKey = GlobalKey();

  late Map im_param;

  @override
  void initState() {
    super.initState();
    im_param = jsonDecode(widget.param);
    // listSourceRepository = new ProductBloc();
    listSourceRepository = Provider.of<ProductBloc>(context, listen: false)..init();

    listSourceRepository.criteria = {
      "category_id": im_param['category_id'],
      "keyword": im_param['keyword'],
    };
    listSourceRepository.refresh();
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      RenderBox renderBox = cartKey.currentContext?.findRenderObject() as RenderBox;
      cartOffset = renderBox.localToGlobal(Offset.zero);
      AppSession.prodListCart = cartOffset;
      // Provider.of<ProductBloc>(context, listen: false).init(listSourceRepository);
    });
    AppSession.prodListRoot = rootKey;
  }

  @override
  void dispose() {
    // listSourceRepository?.dispose();
    // Provider.of<ProductBloc>(context, listen: false)..refresh();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var lv_title;
    if ((im_param['category_name'] ?? '').isNotEmpty) lv_title = im_param['category_name'];
    if ((im_param['keyword'] ?? '').isNotEmpty) lv_title = im_param['keyword'];
    return Consumer<ProductBloc>(
      builder: (context, listSourceRepository, child) => Material(
        color: Colors.white,
        child: LoadingMoreCustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              brightness: Brightness.light,
              title: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Navigator.pop(context);
                },
                child: Container(
                  padding: EdgeInsets.only(right: 15.w),
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.chevron_left,
                        color: AppColor.blackMain,
                        size: 32,
                      ),
                      Text(' ${lv_title}', style: TextStyle(color: AppColor.blackMain)),
                    ],
                  ),
                ),
              ),
              automaticallyImplyLeading: false,
              // backgroundColor: Colors.white,
              pinned: true,
              actions: <Widget>[
                Container(
                  key: rootKey,
                  // child: Column(
                  //   children: <Widget>[
                  //     // HomeCartBlock(iv_key: test),
                  //     Container(),
                  //     Container(
                  margin: EdgeInsets.only(right: 37.w),
                  // padding: EdgeInsets.all(0.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        child: Consumer<CartBloc>(
                          builder: (context, _cart, child) => Builder(
                            builder: (context) {
                              return GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  if (_cart.amount == 0)
                                    AppPopupService.showAlertSimple(
                                        'I', '购物车是空的', '请先选择商品加入购物车，然后再结账哦');
                                  else
                                    App.router.navigateTo(context, AppRoutes.orderCart);
                                },
                                child: Badge(
                                  badgeColor: Colors.red,
                                  toAnimate: true,
                                  shape: BadgeShape.circle,
                                  borderRadius: BorderRadius.circular(20),
                                  animationType: BadgeAnimationType.scale,
                                  child: Image.asset(
                                    'assets/order/cart_circle.png',
                                    key: cartKey,
                                  ),
                                  badgeContent: Text(_cart.amount.toString(),
                                      style: TextStyle(color: Colors.white)),
                                ),
                              );
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SliverPersistentHeader(
              pinned: true,
              delegate: _subCateBar(
                collapsedHeight: 60.h,
                expandedHeight: 60.h,
                showHeading: true,
                rep: listSourceRepository,
              ),
            ),
            LoadingMoreSliverList(
              SliverListConfig<Map>(
                itemBuilder: _ProductListCateScreenState.generateItem,
                sourceList: listSourceRepository,
//                    showGlowLeading: false,
//                    showGlowTrailing: false,
                padding: EdgeInsets.all(0.0),
                // collectGarbage: (List<int> indexes) {
                //   ///collectGarbage
                //   indexes.forEach((index) {
                //     final item = listSourceRepository[index];
                //   });
                // },
                // viewportBuilder: (int firstIndex, int lastIndex) {
                //   // print("viewport : [$firstIndex,$lastIndex]");
                // },
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Widget _categoryComp(int iv_category_id, String iv_category_name){
  //   var lv_img = 'img_cate_'+iv_category.toString()+'.png';
  //   return Container(
  //     height: (70*3).h,
  //     width: (56 * 3).w,
  //     child: Column(
  //        children: <Widget>[
  //          Image.asset(lv_img),
  //         Text(iv_category_name, style: TextStyle(color: ),
  //        ],
  //     ),
  //   );
  // }

  static Widget generateItem(BuildContext context, Map item, int index) {
    late Offset temp;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        App.router.navigateTo(context, 'product_detail?prod_id=${item['sku_id']}');
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 22.w, vertical: 5.w),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              width: 120.w,
              height: 120.h,
              padding: EdgeInsets.symmetric(
                horizontal: 5.w,
                vertical: 5.h,
              ),
              child: CachedNetworkImage(
                imageUrl: item['image_url'],
                fit: BoxFit.cover,
              ),
            ),
            Container(
              width: 211.w,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                // crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    width: 211.w,
                    height: 70.h,
                    padding: EdgeInsets.only(left: 10.w),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          item['sku_name'],
                          softWrap: true,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: AppColor.nameProduct,
                            fontWeight: FontWeight.normal,
                            fontSize: 15.sp,
                          ),
                        ),
                        Text(
                          item['sku_desc'],
                          softWrap: true,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: AppColor.descProduct,
                            fontWeight: FontWeight.normal,
                            fontSize: 11.sp,
                          ),
                        ),
                        Text(
                          '\$ ' + item['sku_price'] + ' / ' + item['unit_desc'],
                          softWrap: true,
                          maxLines: 1,
                          overflow: TextOverflow.fade,
                          style: TextStyle(
                            color: AppColor.priceProduct,
                            fontWeight: FontWeight.normal,
                            fontSize: 15.sp,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(right: 10.w),
                    height: 50.h,
                    child: Consumer<CartBloc>(
                      builder: (context, _cart, child) => Builder(
                        builder: (context) {
                          return Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              GestureDetector(
                                onTap: () {
                                  _cart.reduceItem(item['sku_id']);
                                },
                                child: Padding(
                                  padding: EdgeInsets.symmetric(horizontal: 10.w),
                                  child: Icon(
                                    // MaterialCommunityIcons.minus_circle_outline,
                                    LineIcons.minusCircle,
                                    color: AppColor.nameProduct,
                                    size: 28,
                                  ),
                                ),
                              ),
                              Container(
                                width: 30.w,
                                alignment: Alignment.center,
                                child: Text(
                                  _cart.itemAmount(item['sku_id']).toString(),
                                  style: TextStyle(
                                    color: AppColor.priceProduct,
                                    fontWeight: FontWeight.normal,
                                    fontSize: 20.sp,
                                  ),
                                ),
                              ),
                              GestureDetector(
                                onPanDown: (details) {
                                  temp = new Offset(
                                      details.globalPosition.dx, details.globalPosition.dy);
                                },
                                onTap: () {
                                  late Function callback;
                                  // setState(() {
                                  _cart.addItem(item);
                                  OverlayEntry entry = OverlayEntry(builder: (ctx) {
                                    return ParabolaAnimateWidget(
                                      AppSession.prodListRoot,
                                      temp,
                                      AppSession.prodListCart,
                                      Icon(
                                        Icons.add_circle,
                                        color: Colors.redAccent,
                                      ),
                                      callback,
                                      duration: 800,
                                    );
                                  });

                                  callback = (status) {
                                    if (status == AnimationStatus.completed) {
                                      entry.remove();
                                    }
                                  };

                                  Overlay.of(AppSession.prodListRoot.currentContext!)!.insert(entry);
                                },
                                child: Padding(
                                  padding: EdgeInsets.symmetric(horizontal: 10.w),
                                  child: Icon(
                                    // MaterialCommunityIcons.plus_circle,
                                    LineIcons.plusCircle,
                                    color: AppColor.nameProduct,
                                    size: 28,
                                  ),
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _subCateBar extends SliverPersistentHeaderDelegate {
  _subCateBar({
    required this.collapsedHeight,
    required this.expandedHeight,
    required this.showHeading,
    required this.rep,
  });

  bool showHeading;
  final double expandedHeight;
  final double collapsedHeight;
  ProductBloc rep;

  @override
  double get minExtent => collapsedHeight;

  @override
  double get maxExtent => math.max(expandedHeight, minExtent);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    print('aaa');
    print(rep.criteria);
    print(rep.sub_cate);
    return //ListView(
        Container(
      color: Colors.white,
      child: Consumer<ProductBloc>(
        builder: (context, _product, child) => Builder(builder: (context) {
          print(_product);
          return ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _product.sub_cate.length, // rep.sub_cate.length ?? 0,
              itemBuilder: (BuildContext context, int index) {
                var _item = _product.sub_cate[index]; // rep.sub_cate[index];
                print(_item);
                return Container(
                  height: 30.h,
                  padding: EdgeInsets.symmetric(
                    horizontal: 8.w,
                    vertical: 12.h,
                  ),
                  child: ElevatedButton(
                    style:ButtonStyle(
                      foregroundColor:  MaterialStateProperty.all((_item['cate2_id'] == rep.criteria['cate2_id'])? AppColor.yellowMain : Colors.grey[300]),
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(30))),
                    ),
                    child: Text(
                      _item['cate2_name'] ?? '',
                      style: TextStyle(color: AppColor.blackMain, fontSize: 15.sp),
                    ),
                    onPressed: () {
                      rep.criteria = {
                        "category_id": _item['category_id'],
                        "keyword": '',
                        "cate2_id": _item['cate2_id'],
                      };
                      rep.refresh();
                    },
                  ),
                );
              });
        }),
      ),
    );
  }

  @override
  bool shouldRebuild(_subCateBar oldDelegate) {
//    return false;
    return expandedHeight != oldDelegate.expandedHeight ||
        collapsedHeight != oldDelegate.collapsedHeight;
  }
}
